//
//  FPS.swift
//  HeadlineNews
//
//  Created by han on 2019/6/28.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

class FPSMonitor: NSObject {
    
    static let shareInstance = FPSMonitor()
    
    private override init() { }
    
    private var displayLink: CADisplayLink! = nil;
    private var count: Int = 0
    private var lastTime:TimeInterval = 0.0
    
    private var label: UILabel?
    
    private func addShowView() {
        label = UILabel(frame: CGRect(x: 200, y: 44, width: 80, height: 40))
        label?.backgroundColor = UIColor(white: 0.2, alpha: 0.8)
        label?.textColor = UIColor(white: 1, alpha: 1)
        label?.textAlignment = .center
        UIApplication.shared.keyWindow?.addSubview(label!)
        label?.text = "0 FPS"
        label?.isUserInteractionEnabled = false
    }
    
    func resetFrame(_ frame: CGRect) {
        label?.frame = frame
    }
    
    func startMonitor() {
        if label == nil {
            addShowView()
        }
        displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
        displayLink.add(to:.main, forMode: RunLoop.Mode.common)
    }
    
    func stopMonitor() {
        displayLink.invalidate()
        displayLink = nil
        label?.removeFromSuperview()
        label = nil
    }
    
    @objc func tick(sender: CADisplayLink) {
        if lastTime == 0.0 {
            lastTime = sender.timestamp
            return
        }
        
        count += 1
        let delta = sender.timestamp - lastTime
        if delta < 1 {
            return
        }
        lastTime = sender.timestamp
        let fps = Double(count) / delta
        count = 0
        label?.text = "\(round(fps)) FPS"
    }
    
}
